package com.hyfd.service.mp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.hyfd.common.BaseJson;
import com.hyfd.common.ExcelUtil;
import com.hyfd.common.GlobalSetHyfd;
import com.hyfd.common.Page;
import com.hyfd.common.utils.StringUtil;
import com.hyfd.dao.mp.DataPkgDao;
import com.hyfd.dao.mp.ProviderDataDiscountDao;
import com.hyfd.dao.mp.ProviderDataPkgDao;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.service.BaseService;

@Service
@Transactional
public class ProviderDataDiscountSer extends BaseService{
	
	public Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	DataPkgDao dataPkgDao;
	@Autowired
	ProviderDataPkgDao providerDataPkgDao;
	@Autowired
	ProviderDataDiscountDao providerDataDiscountDao;
	@Autowired
	ProviderPhysicalChannelDao providerPhysicalChannelDao;
	
	/**
	 * <h5>功能描述:</h5>	跳转到运营商折扣包折扣页面
	 *
	 * @param req
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月30日
	 */
	public String providerDataDiscountListPage(String id,HttpServletRequest req){
		Map<String, Object> providerPhysicalChannel = providerPhysicalChannelDao.selectByPrimaryKey(id);
		req.setAttribute("providerPhysicalChannel", providerPhysicalChannel);
		return "mp/providerDataDiscountList";
	}
	
	/**
	 * <h5>功能描述:</h5>	跳转到运营商折扣包折扣编辑页面
	 *
	 * @param req
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月30日
	 */
	public String providerDataDiscountEditPage(String id,HttpServletRequest req){
		Map<String, Object> providerPhysicalChannel = providerPhysicalChannelDao.selectByPrimaryKey(id);
		req.setAttribute("providerPhysicalChannel", providerPhysicalChannel);
		return "mp/providerDataDiscountEdit";
	}
	
	/**
	 * <h5>功能描述:</h5>	分页获取运营商物理通道折扣信息
	 *
	 * @param req
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月30日
	 */
	public String providerDataDiscountList(HttpServletRequest req){
		StringBuilder sb = new StringBuilder();
		try {
			Map<String, Object> m = getMaps(req); // 封装前台参数为map
			Page p = getPage(m);// 提取分页参数
			int total = getAgentCount(m);
			p.setCount(total);
			int pageNum = p.getCurrentPage();
			int pageSize = p.getPageSize();

			sb.append("{");
			sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
			sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
			sb.append("" + getKey("records") + ":" + p.getCount() + ",");
			sb.append("" + getKey("rows") + ":" + "");

			PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
			List<Map<String, Object>> dataList = providerDataDiscountDao.selectAll(m);
			String dataListJson = BaseJson.listToJson(dataList);
			sb.append(dataListJson);
			sb.append("}");
		} catch (Exception e) {
			getMyLog(e, log);
		}
		
		return sb.toString();
	}
	
	/**
	 * 获取记录数量
	 * @param m
	 * @return
	 */
	public int getAgentCount(Map<String, Object> m){
		int agentCount=0;
		try{
			agentCount=providerDataDiscountDao.selectCount(m);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return agentCount;
	}
	
	/**
	 * <h5>功能描述:</h5>	跳转到运营商折扣设置页面
	 *
	 * @param req
	 * @param id
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月31日
	 */
	public String providerDataDiscountAddPage(HttpServletRequest req,String id){
		try{
			Map<String, Object> m=providerPhysicalChannelDao.getProviderPhysicalChannelById(id);
			req.setAttribute("providerPhysicalChannel", m);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return "mp/providerDataDiscountAdd";
	}
	
	public String providerDataRealDiscountAddPage(HttpServletRequest req,String id){
		try{
			Map<String, Object> m=providerPhysicalChannelDao.getProviderPhysicalChannelById(id);
			req.setAttribute("providerPhysicalChannel", m);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return "mp/providerDataDiscountAdd_real";
	}
	
	/**
	 * <h5>功能描述:</h5>	跳转到运营商折扣编辑页面
	 *
	 * @param req
	 * @param id
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月31日
	 */
	public String providerDataDiscountEditPage(HttpServletRequest req,String id){
		try{
			Map<String, Object> m=providerDataDiscountDao.selectByPrimaryKey(id);
			req.setAttribute("providerDataDiscount", m);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return "mp/providerDataDiscountEdit";
	}
	
	
	/**
	 * <h5>功能描述:</h5>	根据流量包获取对应的运营商流量折扣信息
	 *
	 * @param data_pkg_id
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月8日
	 */
	public String getProviderDataDiscountByDataPkgId(String data_pkg_id){
		StringBuilder sb=new StringBuilder();
		try{
			List<Map<String, Object>> dataList=providerDataDiscountDao.getProviderDataDiscountByDataPkgId(data_pkg_id);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
		
	}
	

	/**
	 * <h5>功能描述:</h5>	根据流量包获取对应的运营商流量折扣信息
	 *
	 * @param data_pkg_id 流量包id
	 * @param providerId 运营商id
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月15日
	 */
	public String getProviderDataDiscountByDataPkgIdAndProvinceId(String data_pkg_id,String providerId){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("data_pkg_id", data_pkg_id);
			map.put("providerId", providerId);
			
			List<Map<String, Object>> dataList=providerDataDiscountDao.getProviderDataDiscountByDataPkgIdAndProvinceId(map);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
		
	}

	/**
	 * <h5>功能描述:</h5>	根据物理运营商通道和运营商查询折扣包信息
	 *
	 * @param providerPhysicalChannelId
	 * @param providerId
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月30日
	 */
	public String getProviderDataDiscountByProviderPhysicalChannelIdAndProvider(String providerPhysicalChannelId,String providerId){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("providerPhysicalChannelId", providerPhysicalChannelId);
			map.put("providerId", providerId);
			
			List<Map<String, Object>> dataList=providerDataDiscountDao.selectAll(map);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
		
	}

	/**
	 * <h5>功能描述:</h5>	新增运营商流量折扣
	 *
	 * @param req
	 * @param getProvincesAndDiscountes 流量包范围及折扣
	 * @param providerPhysicalChannelIdArray 运营商
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月9日
	 */
	public String providerDataDiscountAdd(HttpServletRequest req,String[] provincesAndDiscountes){
		boolean flag=true;
		try{
			Map<String, Object> myData=getMaps(req);
			Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
			
			myData.put("createUser", userInfoMap.get("suId"));//放入创建用户
			String dataPkgName = myData.get("name").toString(); //获取流量包名
			String[] providerPhysicalChannelIdArray = myData.get("providerPhysicalChannelIdes").toString().split(","); //获取流量包名
			String provinceCodeAndDiscount[] = null;
			String discount = "";
			String provinceCode = "";
			
			// 删除指定流量包折扣旧数据
			providerDataDiscountDao.deleteProviderDataDiscountByProviderIdAndDataPkgId(myData);
			
			for (int i = 0; i < providerPhysicalChannelIdArray.length; i++) {
				String providerPhysicalChannelId = providerPhysicalChannelIdArray[i];
				myData.put("providerPhysicalChannelId", providerPhysicalChannelId);
				
				for (int j = 0; j < provincesAndDiscountes.length; j++) {
					provinceCodeAndDiscount = provincesAndDiscountes[j].split("-");
					provinceCode = provinceCodeAndDiscount[0];
					discount = provinceCodeAndDiscount[1];
					
					myData.put("name", dataPkgName + "-" +provinceCode);
					myData.put("provinceCode", provinceCode);
					myData.put("discount", discount);
					// 添加运营商流量折扣信息
					int rows=providerDataDiscountDao.providerDataDiscountAdd(myData);
					if(rows < 1){
						flag = false;
						throw new Exception("插入流量包折扣异常");
					}
				}
			}
		}catch(Exception e){
			getMyLog(e,log);
		}
		return flag+"";		
	}
	
	public String providerDataDiscountAddExt(HttpServletRequest req){
		boolean flag=true;
		try{
			Map<String, Object> myData=getMaps(req);
			Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
			
			myData.put("createUser", userInfoMap.get("suId"));//放入创建用户
			String[] dataPkgDiscount  = myData.get("dataPkgDiscount").toString().split(",");
			
			// 删除指定流量包折扣旧数据
			providerDataDiscountDao.deleteProviderDataDiscount(myData);
			
			for (int i = 0; i < dataPkgDiscount.length; i++) {
				String[] discountInfo = dataPkgDiscount[i].split("-");
				myData.put("name", discountInfo[0]);
				myData.put("dataPkgId", discountInfo[1]);
				myData.put("discount", discountInfo[2]);
				myData.put("realDiscount", discountInfo[3]);
				// 添加运营商流量折扣信息
				int rows=providerDataDiscountDao.providerDataDiscountAdd(myData);
				if(rows < 1){
					flag = false;
					throw new Exception("插入流量包折扣异常");
				}
			}
		}catch(Exception e){
			getMyLog(e,log);
		}
		return flag+"";		
	}
	
	public String providerDataDiscountEdit(HttpServletRequest req){
		boolean flag=false;
		try{
			Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
			Map<String, Object> myData=getMaps(req);
			myData.put("updateUser", userInfoMap.get("suId"));//放入更新用户
			String discountMeg = (String) myData.get("discountMeg");
			String[] m = discountMeg.split(",");
			for(String meg:m){
				String[] split = meg.split("-");
				String id = split[0];
				String discount = split[1];
				Map<String,Object> data = new HashMap<String, Object>();
				data.put("id", id);
				data.put("discount", discount);
				data.put("updateUser", userInfoMap.get("suName"));//放入修改用户	
				int i = providerDataDiscountDao.updateByPrimaryKeySelective(data);
				if(i>0){
					flag=true;
				}else{
					flag=false;
					break;
				}
			}
		}catch(Exception e){
			getMyLog(e,log);
		}
		return flag+"";	
	}
	
	public String providerDataDiscountUpload(HttpServletRequest req,String[] providerPhysicalChannelIdes){
		String result="";
		try{
			Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
			Map<String, Object> map = getMaps(req);
			
			String providerId=req.getParameter("providerId");
			String providerPhysicalChannelId = map.get("providerPhysicalChannelId").toString();
			List<Map<String, Object>> dataPkgList=dataPkgDao.getDataPkgList(map);	//获取流量包信息
			String resultFileName="";
			String savePath=getMyAppPath(req)+GlobalSetHyfd.savePath;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy_MM_dd");
			savePath=savePath+"/"+sdf.format(new Date());
			
			createDir(savePath);
			//---------------------------------文件上传开始
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getServletContext());
			if(multipartResolver.isMultipart(req)){
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req; 
				Iterator<String> iter = multiRequest.getFileNames();
				 while(iter.hasNext()){
					 MultipartFile file = multiRequest.getFile(iter.next());  
		              if(file != null){
		            	  String myFileName = file.getOriginalFilename();
		            	  myFileName=Calendar.getInstance().getTimeInMillis()+myFileName.substring(myFileName.lastIndexOf("."),myFileName.length());
		            	  myFileName=savePath+"/"+myFileName;
		            	  resultFileName=myFileName;
		            	  File myLocalFile=new File(myFileName);
		            	  file.transferTo(myLocalFile);
		              }
				 }
			}
			//------------------------------文件上传结束
			//删除所有折扣数据
			providerDataDiscountDao.deleteProviderDataDiscountByProviderIdAndProviderPhysicalChannelId(map);
			//------------------------------读取excel文件开始
			
			for (int i = 0; i < dataPkgList.size(); i++) {
				Map<String, Object> dataPkg = dataPkgList.get(i);
				Map<String, List<String[]>> mapData=ExcelUtil.readExcel(resultFileName);
				Set<Entry<String, List<String[]>>> setData= mapData.entrySet();
				for(Map.Entry<String, List<String[]>> entry:setData){
	//				String sheetName=entry.getKey();
					List<String[]> sheetData=entry.getValue();
					int rowIndex=0;
					for(String[] col:sheetData){
						if(rowIndex==0){
							rowIndex++;
							continue; // 不读第一行
						}
						Map<String, Object> providerDataDiscountMap=new HashMap<String, Object>();
						providerDataDiscountMap.put("providerPhysicalChannelId", providerPhysicalChannelId);
						providerDataDiscountMap.put("providerId", providerId);
						providerDataDiscountMap.put("name", dataPkg.get("name")+"-"+ col[0]);
						providerDataDiscountMap.put("dataPkgId", dataPkg.get("id"));
						providerDataDiscountMap.put("provinceCode", col[0]);
						providerDataDiscountMap.put("discount", col[1]);
						providerDataDiscountMap.put("createUser", userInfoMap.get("suId"));
						//将折扣数据导入数据库
						providerDataDiscountDao.providerDataDiscountAdd(providerDataDiscountMap);
						rowIndex++;
					}
				}
			}
			
			
			//------------------------------读取excel文件结束
			
		result="true";
		}catch(Exception e){
			getMyLog(e,log);
			result=e.getMessage();
		}
		return result+"";	
	}
	
	/**
	 * <h5>功能描述:</h5>	找出新增的运营商
	 *
	 * @param dataPkgId
	 * @param providerPhysicalChannelIdes
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年3月8日
	 */
	private String[] getNewProvider(String dataPkgId,String[] providerPhysicalChannelIdes){
		List<String> list = null;
		
		if (null != providerPhysicalChannelIdes && providerPhysicalChannelIdes.length > 0) {
			// 将provinceCodeList转换成list
			list = StringUtil.arrayToList(providerPhysicalChannelIdes);
			
			// 根据流量包id查询所属的运营商
			List<Map<String, Object>>providerList=providerDataDiscountDao.getProviderDataDiscountByDataPkgId(dataPkgId);
			for (int i = 0; i < providerList.size(); i++) {
				String providerId = providerList.get(i).get("provider_id").toString();
				if (list.contains(providerId)) {
					list.remove(providerId);
				}
			}
		}
		return list.toArray(new String[list.size()]);
	}
	
	/**
	 * <h5>功能描述:</h5>	根据物理运营商id、运营商、流量包类型获取流量包范围
	 *
	 * @param req
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年4月1日
	 */
	public String selectProvinceCode(HttpServletRequest req){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> maps = getMaps(req);
			List<Map<String, Object>> dataList=providerDataDiscountDao.selectProvinceCode(maps);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
	}
	
	/**
	 * @功能描述：	折扣设置页面获取满足条件的流量包折扣信息
	 *
	 * @作者：zhangpj		@创建时间：2017年5月16日
	 * @param req
	 * @return
	 */
	public String selectProviderDataDiscount(HttpServletRequest req){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> maps = getMaps(req);
			List<Map<String, Object>> dataList=providerDataDiscountDao.selectAll(maps);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
	}
	
	/**
	 * <h5>功能描述:</h5>	根据物理运营商id、运营商、流量包类型、流量包范围获取运营商折扣信息
	 *
	 * @param req
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年4月1日
	 */
	public String selectDataPkgAndDiscount(HttpServletRequest req){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> maps = getMaps(req);
			List<Map<String, Object>> dataList=providerDataDiscountDao.selectDataPkgAndDiscount(maps);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
	}
}
